package com.rhb.ca.web.util;

import java.util.*;
import java.util.regex.*;

/**
 * This class is an object representation of a protected resource
 */

public class ProtectedResource implements java.io.Serializable {

    private String name = null;
    private ArrayList urlPatterns = null;
    private ArrayList roles = null;

    public ProtectedResource (String name, ArrayList urlPatterns, ArrayList roles) {
        this.name = name;
        this.urlPatterns = urlPatterns;
        this.roles = roles;
    }

    public String getName() {
        return name;
    }

    public ArrayList getURLPatterns() {
        return urlPatterns;
    }
    
    public boolean existURL(String url){
    	boolean flag = false;
	    if(urlPatterns!=null){
	    	for(int i=0; i<urlPatterns.size(); i++){
		        String urlPattern = (String)urlPatterns.get(i);
		        Pattern p = Pattern.compile(urlPattern.toLowerCase());
		        Matcher m = p.matcher(url.toLowerCase());
		        
		        if (m.matches()) {
		            flag = true;
		            break;
		        }
	    	}
	    }
	    return flag;
    }
    
    public boolean existRole(String role){
    	boolean flag = false;
	    if(roles!=null){
	    	for(int i=0; i<roles.size(); i++){
		        String ro = (String)roles.get(i);
		        if (ro.equals(role)) {   
		            flag = true;
		            break;
		        }
	    	}
	    }
	    return flag;
    }

    public ArrayList getRoles() {
        return roles;
    }

    public String toString() {
    	StringBuffer sb = new StringBuffer("ProtectedResource {");
    	sb.append("name=[");
    	sb.append(name);
    	sb.append("],");
    	sb.append("urls=[");
    	if(urlPatterns!=null && urlPatterns.size()!=0){
    		for(int i=0; i<urlPatterns.size(); i++){
    			sb.append((String)urlPatterns.get(i));
    			if(i!=urlPatterns.size()-1){
    				sb.append(",");
    			}
    		}
    	}
    	sb.append("],");
    	sb.append("roles=[");
    	if(roles!=null && roles.size()!=0){
    		for(int i=0; i<roles.size(); i++){
    			sb.append((String)roles.get(i));
    			if(i!=roles.size()-1){
    				sb.append(",");
    			}
    		}
    	}
    	sb.append("]");
    	sb.append("}");
        return sb.toString();
    }
}
